package util
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import view.MessagePanel;
	import view.event.LocalDataReadyEvent;

	public class LoadUtil extends EventDispatcher
	{
		private var file:FileReference;
		public function LoadUtil()
		{
		}
		public function load():void
		{
			clearFile();
			file = new FileReference();
			file.addEventListener(Event.SELECT, selectHandler);
			file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			file.addEventListener(Event.COMPLETE,completeHandler);
			file.addEventListener(Event.CANCEL,cannel);
			file.addEventListener(Event.OPEN,open);
			file.browse([new FileFilter("Images", "*.jpg;*.gif;*.png;*.JPG;*.GIF;*.PNG")]);
	//		file.browse([new FileFilter("Images", "*.jpg")]);
		}
		private function clearFile():void{
			if(file){
				file.removeEventListener(Event.SELECT, selectHandler);
				file.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				file.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
				file.removeEventListener(Event.COMPLETE,completeHandler);
				file.removeEventListener(Event.CANCEL,cannel);
				file.removeEventListener(Event.OPEN,open);
				file=null;
			}
		}
		private function selectHandler(event:Event):void {
			var file:FileReference = FileReference(event.target);
			file.load();
		}
		private function open(e:Event):void
		{
			var num:Number=(file.size/1024/1024);
			if(num<CutPhotoConfig.min)
			{
				MessagePanel.getInstance().showLoading("选择的文件不能小于"+CutPhotoConfig.min+"M")
				clearFile();
			}
			if(num>CutPhotoConfig.max)
			{
				MessagePanel.getInstance().showLoading("选择的文件不能大于"+CutPhotoConfig.max+"M")
				clearFile();
			}
		}
		private function cannel(e:Event):void{
		//	MessagePanel.getInstance().setText("取消了选择文件");
		}
		public function ioErrorHandler(event:IOErrorEvent):void {
			trace("加载本地图片失败");
			MessagePanel.getInstance().showLoading("加载本地图片失败");
		}
		
		private function progressHandler(event:ProgressEvent):void {
			trace("加载本地图片中...");
			MessagePanel.getInstance().showLoading("加载本地图片中...",true,0);
			
		}
		private var loader:Loader=new Loader;
		private function completeHandler(e:Event):void {
			MessagePanel.getInstance().hideLoading();
			var by:ByteArray=(e.target.data as ByteArray);
			dispatchEvent(new LocalDataReadyEvent(e.target.data));
		}
	}
}